#import "MemoryBoardViewController.h"
#import "AddItemViewController.h"

@interface MemoryBoardViewController () <AddItemViewControllerDelegate>
@property (nonatomic, strong) UILabel *statsContent; // 添加统计标签的引用
@end

@implementation MemoryBoardViewController

- (void)saveMemoryItems {
    [[NSUserDefaults standardUserDefaults] setObject:self.memoryItems forKey:@"memoryItems"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)loadMemoryItems {
    NSArray *saved = [[NSUserDefaults standardUserDefaults] objectForKey:@"memoryItems"];
    if (saved) {
        self.memoryItems = [saved mutableCopy];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"黄金记忆板";
    
    // 设置渐变背景
    CAGradientLayer *backgroundGradient = [CAGradientLayer layer];
    backgroundGradient.colors = @[(__bridge id)[UIColor colorWithRed:0.96 green:0.98 blue:1.0 alpha:1.0].CGColor,
                                  (__bridge id)[UIColor colorWithRed:0.94 green:0.96 blue:1.0 alpha:1.0].CGColor];
    backgroundGradient.frame = self.view.bounds;
    [self.view.layer insertSublayer:backgroundGradient atIndex:0];
    // 设置导航栏 - 使用 back 图片
    UIImage *backImage = [UIImage imageNamed:@"back"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage style:UIBarButtonItemStylePlain target:self action:@selector(cancelAction)];
    // 优化导航栏
//    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.26 green:0.54 blue:0.96 alpha:1.0];
    self.navigationController.navigationBar.titleTextAttributes = @{
        NSForegroundColorAttributeName: [UIColor blackColor],
        NSFontAttributeName: [UIFont systemFontOfSize:20 weight:UIFontWeightMedium]
    };
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    
    [self loadMemoryItems];
    if (!self.memoryItems) {
        self.memoryItems = [NSMutableArray arrayWithArray:@[
            @{@"title":@"下午打球", @"desc":@"张大爷三点打球", @"time":@"09:00", @"done":@NO, @"priority":@"high"}
        ]];
    }
    
    [self setupStatsCard];
    [self setupTableView];
    [self setupAddButton];
}
- (void)cancelAction {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setupStatsCard {
    // 添加顶部统计卡片
    UIView *statsCard = [[UIView alloc] initWithFrame:CGRectMake(20, 100, self.view.bounds.size.width - 40, 80)];
    statsCard.backgroundColor = [UIColor whiteColor];
    statsCard.layer.cornerRadius = 20;
    statsCard.layer.shadowColor = [UIColor colorWithRed:0.26 green:0.54 blue:0.96 alpha:0.1].CGColor;
    statsCard.layer.shadowOpacity = 1;
    statsCard.layer.shadowOffset = CGSizeMake(0, 4);
    statsCard.layer.shadowRadius = 10;
    [self.view addSubview:statsCard];
    
    UILabel *statsTitle = [[UILabel alloc] initWithFrame:CGRectMake(20, 15, statsCard.bounds.size.width - 40, 20)];
    statsTitle.text = @"今日进度";
    statsTitle.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
    statsTitle.textColor = [UIColor colorWithRed:0.3 green:0.3 blue:0.3 alpha:1.0];
    [statsCard addSubview:statsTitle];
    
    self.statsContent = [[UILabel alloc] initWithFrame:CGRectMake(20, 40, statsCard.bounds.size.width - 40, 25)];
    self.statsContent.font = [UIFont systemFontOfSize:18 weight:UIFontWeightBold];
    self.statsContent.textColor = [UIColor colorWithRed:0.26 green:0.54 blue:0.96 alpha:1.0];
    [statsCard addSubview:self.statsContent];
    
    [self updateStatsDisplay];
}

- (void)setupTableView {
    // 表格
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 190, self.view.bounds.size.width, self.view.bounds.size.height - 290) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.tableView];
}

- (void)setupAddButton {
    // 优化添加按钮
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.frame = CGRectMake(self.view.bounds.size.width - 80, self.view.bounds.size.height - 120, 60, 60);
    
    // 创建渐变背景
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.colors = @[(__bridge id)[UIColor colorWithRed:0.26 green:0.54 blue:0.96 alpha:1.0].CGColor,
                        (__bridge id)[UIColor colorWithRed:0.20 green:0.45 blue:0.85 alpha:1.0].CGColor];
    gradient.startPoint = CGPointMake(0, 0);
    gradient.endPoint = CGPointMake(1, 1);
    gradient.frame = CGRectMake(0, 0, 60, 60);
    gradient.cornerRadius = 30;
    [addBtn.layer insertSublayer:gradient atIndex:0];
    
    addBtn.layer.cornerRadius = 30;
    addBtn.layer.shadowColor = [UIColor colorWithRed:0.26 green:0.54 blue:0.96 alpha:0.3].CGColor;
    addBtn.layer.shadowOpacity = 1;
    addBtn.layer.shadowOffset = CGSizeMake(0, 6);
    addBtn.layer.shadowRadius = 12;
    [addBtn setTitle:@"+" forState:UIControlStateNormal];
    [addBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    addBtn.titleLabel.font = [UIFont systemFontOfSize:28 weight:UIFontWeightLight];
    [addBtn addTarget:self action:@selector(addMemoryItem) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addBtn];
}

- (void)updateStatsDisplay {
    // 统计信息
    NSInteger totalItems = self.memoryItems.count;
    NSInteger completedItems = 0;
    for (NSDictionary *item in self.memoryItems) {
        if ([item[@"done"] boolValue]) completedItems++;
    }
    
    self.statsContent.text = [NSString stringWithFormat:@"已完成 %ld/%ld 项任务", (long)completedItems, (long)totalItems];
}

#pragma mark - TableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.memoryItems.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 110;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"MemoryCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    cell.selectionStyle = UITableViewCellSeparatorStyleNone;
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
        cell.backgroundColor = [UIColor clearColor];
        UIView *bg = [[UIView alloc] initWithFrame:CGRectMake(16, 8, self.view.bounds.size.width-32, 94)];
        bg.backgroundColor = [UIColor whiteColor];
        bg.layer.cornerRadius = 18;
        bg.tag = 1001;
        [cell.contentView addSubview:bg];
        
        UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(24, 18, self.view.bounds.size.width-120, 24)];
        title.font = [UIFont boldSystemFontOfSize:18];
        title.textColor = [UIColor colorWithRed:0.22 green:0.22 blue:0.22 alpha:1.0];
        title.tag = 1002;
        [cell.contentView addSubview:title];
        
        UILabel *desc = [[UILabel alloc] initWithFrame:CGRectMake(24, 44, self.view.bounds.size.width-120, 20)];
        desc.font = [UIFont systemFontOfSize:15];
        desc.textColor = [UIColor grayColor];
        desc.tag = 1003;
        [cell.contentView addSubview:desc];
        
        UILabel *time = [[UILabel alloc] initWithFrame:CGRectMake(self.view.bounds.size.width-100, 18, 60, 22)];
        time.font = [UIFont systemFontOfSize:16];
        time.textColor = [UIColor colorWithRed:1.0 green:0.54 blue:0.40 alpha:1.0];
        time.textAlignment = NSTextAlignmentRight;
        time.tag = 1004;
        [cell.contentView addSubview:time];
        
        UIButton *doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        doneBtn.frame = CGRectMake(self.view.bounds.size.width-90, 50, 60, 32);
        doneBtn.layer.cornerRadius = 16;
        doneBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        doneBtn.tag = 1005;
        [doneBtn addTarget:self action:@selector(toggleDone:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:doneBtn];
    }
    NSDictionary *item = self.memoryItems[indexPath.row];
    UILabel *title = [cell.contentView viewWithTag:1002];
    UILabel *desc = [cell.contentView viewWithTag:1003];
    UILabel *time = [cell.contentView viewWithTag:1004];
    UIButton *doneBtn = [cell.contentView viewWithTag:1005];
    title.text = item[@"title"];
    desc.text = item[@"desc"];
    time.text = item[@"time"];
    BOOL done = [item[@"done"] boolValue];
    [doneBtn setTitle:done ? @"已完成" : @"待完成" forState:UIControlStateNormal];
    doneBtn.backgroundColor = done ? [UIColor colorWithRed:0.36 green:0.78 blue:0.47 alpha:1.0] : [UIColor colorWithRed:1.0 green:0.54 blue:0.40 alpha:1.0];
    [doneBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    doneBtn.accessibilityIdentifier = [NSString stringWithFormat:@"%ld", (long)indexPath.row];
    return cell;
}

// 切换完成状态
- (void)toggleDone:(UIButton *)sender {
    NSInteger idx = [sender.accessibilityIdentifier integerValue];
    NSMutableDictionary *item = [self.memoryItems[idx] mutableCopy];
    item[@"done"] = @(![item[@"done"] boolValue]);
    self.memoryItems[idx] = item;
    [self saveMemoryItems];
    [self.tableView reloadData];
    [self updateStatsDisplay]; // 更新统计显示
}

// 选中事项，弹出详情
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *item = self.memoryItems[indexPath.row];
    NSString *msg = [NSString stringWithFormat:@"%@\n%@\n时间：%@", item[@"title"], item[@"desc"], item[@"time"]];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"事项详情" message:msg preferredStyle:UIAlertControllerStyleAlert];
    
    // 修复编辑按钮，添加跳转到编辑页面的逻辑
    [alert addAction:[UIAlertAction actionWithTitle:@"编辑" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self editItemAtIndex:indexPath.row];
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [self.memoryItems removeObjectAtIndex:indexPath.row];
        [self saveMemoryItems];
        [self.tableView reloadData];
        [self updateStatsDisplay]; // 更新统计显示
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"关闭" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

// 新增编辑事项的方法
- (void)editItemAtIndex:(NSInteger)index {
    NSDictionary *item = self.memoryItems[index];
    
    AddItemViewController *editVC = [[AddItemViewController alloc] init];
    editVC.delegate = self;
    
    // 设置编辑模式和数据
    editVC.isEditMode = YES;
    editVC.editingIndex = index;
    editVC.editingItem = item;
    
    [self.navigationController pushViewController:editVC animated:YES];
}

// 添加缺失的 addMemoryItem 方法
- (void)addMemoryItem {
    AddItemViewController *addVC = [[AddItemViewController alloc] init];
    addVC.delegate = self;
    
    // 设置为添加模式
    addVC.isEditMode = NO;
    
    [self.navigationController pushViewController:addVC animated:YES];
}

#pragma mark - AddItemViewControllerDelegate

- (void)didAddNewItem:(NSDictionary *)item {
    [self.memoryItems addObject:item];
    [self saveMemoryItems];
    
    // 刷新UI
    [self.tableView reloadData];
    [self updateStatsDisplay];
    
    // 显示成功提示
    UIAlertController *successAlert = [UIAlertController alertControllerWithTitle:@"✅ 添加成功" message:@"新事项已添加到您的记忆板" preferredStyle:UIAlertControllerStyleAlert];
    [successAlert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:successAlert animated:YES completion:nil];
}

// 新增编辑完成的代理方法
- (void)didEditItem:(NSDictionary *)item atIndex:(NSInteger)index {
    if (index >= 0 && index < self.memoryItems.count) {
        self.memoryItems[index] = item;
        [self saveMemoryItems];
        
        // 刷新UI
        [self.tableView reloadData];
        [self updateStatsDisplay];
        
        // 显示成功提示
        UIAlertController *successAlert = [UIAlertController alertControllerWithTitle:@"✅ 更新成功" message:@"事项已成功更新" preferredStyle:UIAlertControllerStyleAlert];
        [successAlert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:successAlert animated:YES completion:nil];
    }
}

@end
